<template>
  <el-dialog
    width="710px"
    :visible="show === 0"
    :append-to-body="true"
    :show-close="false"
    :destroy-on-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div slot="title" class="title_close">
      <!-- 预警 -->
      <div class="title">{{ $t("inccom.warn_dialog.56hz0lui2pw0") }}</div>
      <img src="@/assets/img/icon_gb1.png" class="close" @click="hide" />
    </div>
    <div class="warn_list">
      <div
        class="warn_bar"
        @click="checkNav(index)"
        v-for="(item, index) in list"
        :key="index"
        :class="navKey === index ? 'bt-blue' : 'bt-gray'"
      >
        <img
          class="warn_icon"
          :src="navKey === index ? item.img1 : item.img2"
          alt=""
        />
        <span>{{ item.name }}</span>
      </div>
      <el-autocomplete
        class="search"
        v-model="valur"
        :popper-append-to-body="false"
        :fetch-suggestions="querySearch"
        :placeholder="$t('m.inputStock')"
        :trigger-on-focus="false"
        @select="handleSelect"
        clearable
        ref="elautocomplete"
      >
        <img src="@/assets/img/icon_ss.png" slot="suffix" />
        <template slot-scope="{ item }">
          <div class="name">{{ item.name }}</div>
          <span class="addr"
            >{{ item.symbol }}({{ item.market | Market }})</span
          >
        </template>
      </el-autocomplete>
    </div>

    <!-- 新建预警 -->
    <div
      class="warn_new"
      v-if="(stockInfo.detail || stockInfo.detail != null) && navKey === 1"
    >
      <div class="stock_info">
        <div class="stock_icon">
          <img
            class="type_icon"
            :src="
              stockInfo.detail.market == 'HKEX'
                ? HKicon
                : stockInfo.detail.market == 'US'
                ? USicon
                : stockInfo.detail.market == 'SSE'
                ? SHicon
                : SZicon
            "
            alt=""
          />
          <span class="stock_name">{{
            `${stockInfo.detail.name} (${stockInfo.detail.symbol})`
          }}</span>
        </div>
        <!-- 涨跌信息 -->
        <div style="padding-top: 2px">
          <span class="stock_name">
            {{ $t("inccom.warn_dialog.56hz0lui3d80") }}
          </span>
          <span
            class="stock_gain"
            :class="
              stockInfo.detail.gain > 0
                ? 'red'
                : stockInfo.detail.gain == 0
                ? ''
                : 'green'
            "
          >
            {{
              Number(stockInfo.detail.latestPrice).toFixed(
                stockInfo.detail.precision
              )
            }}
          </span>
          <span class="stock_name">
            {{ $t("inccom.warn_dialog.56hz0lui3i00") }}
          </span>
          <span
            class="stock_gain"
            :class="
              stockInfo.detail.gain > 0
                ? 'red'
                : stockInfo.detail.gain == 0
                ? ''
                : 'green'
            "
          >
            {{ stockInfo.detail.gain > 0 ? "+" : "" }}{{ parseFloat(stockInfo.detail.gain * 100) | toFixed(2) }}%
          </span>
        </div>
      </div>
      <div class="warn_content">
        <div class="warn_content_title">
          {{ $t("inccom.warn_dialog.56hz0lui3m00") }}
        </div>
        <div class="warn_form">
          <div class="form_item">
            <span class="form_title">{{
              $t("inccom.warn_dialog.56hz0lui3pk0")
            }}</span>
            <input
              title=" "
              type="Number"
              step="0.0001"
              v-model="warnForm.targetHigh"
              :placeholder="$t('inccom.warn_dialog.56hz0lui3ts0')"
            />
          </div>
          <div class="form_item">
            <span class="form_title">{{
              $t("inccom.warn_dialog.56hz0lui3x00")
            }}</span>
            <input
              title=" "
              type="Number"
              step="0.0001"
              v-model="warnForm.targetLow"
              :placeholder="$t('inccom.warn_dialog.56hz0lui3ts0')"
            />
          </div>
        </div>
        <div class="warn_form">
          <div class="form_item">
            <span class="form_title">{{
              $t("inccom.warn_dialog.56hz0lui40c0")
            }}</span>
            <input
              title=" "
              type="Number"
              step="0.01"
              v-model="warnForm.dayGain"
              :placeholder="$t('inccom.warn_dialog.56hz0lui43g0')"
            />
            <span class="form_unit">%</span>
          </div>
          <div class="form_item">
            <span class="form_title">{{
              $t("inccom.warn_dialog.56hz0lui46k0")
            }}</span>
            <input
              title=" "
              type="Number"
              step="0.01"
              v-model="warnForm.dayDecline"
              :placeholder="$t('inccom.warn_dialog.56hz0lui43g0')"
            />
            <span class="form_unit">%</span>
          </div>
        </div>
      </div>
      <div class="new_bt">
        <button class="bt-blue" @click="setWarn">
          {{ $t("inccom.warn_dialog.56hz04si4vk0") }}
        </button>
        <button class="bt-gray" type="primary" @click="hide">
          {{ $t("inccom.warn_dialog.56hz0awi4vk0") }}
        </button>
      </div>
    </div>
    <!-- 预警列表 -->
    <div class="warn_lists" v-show="navKey === 0">
      <div class="warn_lists_nav">
        <div class="stock_sort">
          <div
            :class="stockSortKey === index ? 'hover' : ''"
            v-for="(item, index) of stockSortItem"
            @click="switchSort(index)"
            :key="index"
            class="stock_item"
          >
            {{ `${item.name} (${item.total})` }}
          </div>
        </div>
        <img
          class="reflash_icon"
          @click="reflash"
          src="@/assets/img/icon_sx.png"
          alt=""
        />
      </div>
      <!-- 全部股票预警 -->
      <WarnItem
        @edit="edit"
        key="total"
        @totalChange="totalChange"
        ref="totalWarn"
        type=""
        v-show="stockSortKey == 0"
      ></WarnItem>
      <!-- 香港股票预警 -->
      <WarnItem
        @edit="edit"
        key="hk"
        @totalChange="totalChange"
        ref="hkWarn"
        type="HK"
        v-show="stockSortKey == 1"
      ></WarnItem>
      <!-- 美股预警 -->
      <WarnItem
        @edit="edit"
        key="us"
        @totalChange="totalChange"
        ref="usWarn"
        type="US"
        v-show="stockSortKey == 2"
      ></WarnItem>
      <!-- 沪深预警 -->
      <WarnItem
        @edit="edit"
        key="cn"
        @totalChange="totalChange"
        ref="cnWarn"
        type="CN"
        v-show="stockSortKey == 3"
      ></WarnItem>
    </div>
    <WarnHistory
      v-show="navKey === 2"
      ref="historyList"
      :navKey="navKey"
    ></WarnHistory>
  </el-dialog>
</template>

<script>
import dayjs from "dayjs";
import WarnItem from "./WarnItem";
import WarnHistory from "./WarnHistory";
import { numMulti } from "@/assets/js/calculation.js";
import {get_search, post_history} from '@/assets/js/API/user.js';
import {post_warn, get_warn} from '@/assets/js/API/user.js';
export default {
  components: {
    WarnItem,
    WarnHistory,
  },
  props: {
    warnNavKey: Number,
    show: Number,
  },
  data() {
    return {
      list: [
        {
          name: this.$t("inccom.warn_dialog.56hz0lui4d00"),
          img1: require("@/assets/img/icon_yjlbb.png"),
          img2: require("@/assets/img/icon_yjlbh.png"),
        },
        {
          name: this.$t("inccom.warn_dialog.56hz0lui4g00"),
          img1: require("@/assets/img/icon_xjyjb.png"),
          img2: require("@/assets/img/icon_zjyjh.png"),
        },
        {
          name: this.$t("inccom.warn_dialog.56hz0lui4j40"),
          img1: require("@/assets/img/icon_yjlsb.png"),
          img2: require("@/assets/img/icon_yjlsh.png"),
        },
      ],
      HKicon: require("@/assets/img/icon_hk.png"),
      USicon: require("@/assets/img/icon_us.png"),
      SHicon: require("@/assets/img/icon_sh.png"),
      SZicon: require("@/assets/img/icon_sz(1).png"),
      // 预警表单信息
      warnId: "", // 预警ID
      warnForm: {
        targetHigh: null,
        targetLow: null,
        dayGain: null,
        dayDecline: null,
      },
      navKey: 0, // 预警导航切换
      stockSortItem: [
        {
          name: this.$t("inccom.warn_dialog.56hz0lui4m40"),
          total: 0,
        },
        {
          name: this.$t("inccom.warn_dialog.56hz0lui4pc0"),
          total: 0,
        },
        {
          name: this.$t("inccom.warn_dialog.56hz0lui4so0"),
          total: 0,
        },
        {
          name: this.$t("inccom.warn_dialog.56hz0lui4vk0"),
          total: 0,
        },
      ], // 股票分类
      stockSortKey: 0, // 股票分类切换
      valur: "", // 搜索内容
    };
  },
  methods: {
    hide() {
      this.navKey = 0;
      this.warnForm = {
        targetHigh: null,
        targetLow: null,
        dayGain: null,
        dayDecline: null,
      };
      this.$emit("hides");
    },
    // 点击切换nav
    checkNav(index) {
      this.navKey = index;
      if (index === 0) {
        this.reflash();
      } else if (index === 1) {
        this.judge(this.StockData);
      } else {
        // console.log("打印",this.$refs.historyList)
        this.$refs.historyList.getHistory();
      }
    },
    // 刷新预警列表
    reflash() {
      this.$refs.totalWarn.init();
      this.$refs.totalWarn.getWarnList(1, "");
      this.$refs.hkWarn.init();
      this.$refs.hkWarn.getWarnList(1, "HK");
      this.$refs.usWarn.init();
      this.$refs.usWarn.getWarnList(1, "US");
      this.$refs.cnWarn.init();
      this.$refs.cnWarn.getWarnList(1, "CN");
    },
    // 获取子组件的总长度
    totalChange(total, type) {
      if (type === "HK") {
        this.stockSortItem[1].total = total;
      } else if (type === "US") {
        this.stockSortItem[2].total = total;
      } else if (type === "CN") {
        this.stockSortItem[3].total = total;
      } else {
        this.stockSortItem[0].total = total;
      }
    },
    // 搜索接口
    async querySearch(queryString, cb) {
      const res = await get_search({
        //搜索接口
        keyword: queryString,
      });
      if (res.code !== 1) return this.$message.error(res.msg);
      this.$refs.elautocomplete.activated = true;
      let results = queryString
        ? res.data.list.filter(this.createFilter(queryString))
        : res.data.list;
      // console.log(results);
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return restaurant;
      };
    },
    // 选择搜索股票
    handleSelect(item) {
      var obj = {
        symbol: item.symbol,
        market: item.market,
        securityType: item.securityType,
      };
      this.$store.dispatch("SetStockData", obj);
      this.historyAdd(obj);
      this.warnId = "";
      this.judge(item);
      this.warnForm = {
        targetHigh: null,
        targetLow: null,
        dayGain: null,
        dayDecline: null,
      };
      console.log(this.warnId, this.$t("inccom.warn_dialog.56hz0lui4yc0"));
      if (this.warnId && this.warnId != "") {
        // 请求预警详情
        this.getWarnDetail(this.warnId);
      }
      this.navKey = 1;
    },
    // 判断当前股票是否在预警列表中
    judge(item) {
      if (this.$refs.totalWarn.warnStockList.length > 0) {
        let warn = this.$refs.totalWarn.warnStockList;
        for (let i of warn) {
          // 如果搜索股票在预警列表中存在，跳转到预警列表，否则留在新建列表
          if (i.symbol == item.symbol) {
            this.warnId = i.id;
            if (Number(i.targetHigh) != 0)
              this.warnForm.targetHigh = i.targetHigh;
            else this.warnForm.targetHigh = null;
            if (Number(i.targetLow) != 0) this.warnForm.targetLow = i.targetLow;
            else this.warnForm.targetLow = null;
            if (Number(i.dayGain) != 0)
              this.warnForm.dayGain = numMulti(Number(i.dayGain), 100);
            else this.warnForm.dayGain = null;
            if (Number(i.dayDecline) != 0)
              this.warnForm.dayDecline = numMulti(Number(i.dayDecline), 100);
            else this.warnForm.dayDecline = null;
            break;
          }
        }
      }
    },
    //  股票搜索历史 GET 获取 POST 插入 /api/search/history
    async historyAdd(item) {
      var obj = {
        securityType: item.securityType,
        symbol: item.symbol,
        market: item.market,
      };
      const res = await post_history(obj);
      if (res.code != 1) return this.$message.error(res.msg);
    },
    // 请求预警详情
    async getWarnDetail(warnId) {
      const res = await get_warn({
          warnId: warnId,
        });
      if (res.code != 1) return this.$message.error(res.msg);
      if (Number(res.data.targetHigh) != 0)
        this.warnForm.targetHigh = res.data.targetHigh;
      else this.warnForm.targetHigh = null;
      if (Number(res.data.targetLow) != 0)
        this.warnForm.targetLow = res.data.targetLow;
      else this.warnForm.targetLow = null;
      if (Number(res.data.dayGain) != 0)
        this.warnForm.dayGain = (res.data.dayGain * 100).toFixed(2);
      else this.warnForm.dayGain = null;
      if (Number(res.data.dayDecline) != 0)
        this.warnForm.dayDecline = (res.data.dayDecline * 100).toFixed(2);
      else this.warnForm.dayDecline = null;
    },
    // 切换股票分类,清空股票数据防止，多余重复数据注入到列表
    switchSort(index) {
      if (index == 0) {
        this.$refs.totalWarn.init();
        this.$refs.totalWarn.getWarnList(1, "");
      } else if (index == 1) {
        this.$refs.hkWarn.init();
        this.$refs.hkWarn.getWarnList(1, "HK");
      } else if (index == 2) {
        this.$refs.usWarn.init();
        this.$refs.usWarn.getWarnList(1, "US");
      } else {
        this.$refs.cnWarn.init();
        this.$refs.cnWarn.getWarnList(1, "CN");
      }
      this.stockSortKey = index;
    },
    // 编辑预警信息
    edit(item) {
      var obj = {
        symbol: item.symbol,
        market: item.market,
        securityType: item.securityType,
      };
      this.$store.dispatch("SetStockData", obj);
      if (Number(item.targetHigh) != 0)
        this.warnForm.targetHigh = item.targetHigh;
      else this.warnForm.targetHigh = null;
      if (Number(item.targetLow) != 0) this.warnForm.targetLow = item.targetLow;
      else this.warnForm.targetLow = null;
      if (Number(item.dayGain) != 0)
        this.warnForm.dayGain = (item.dayGain * 100).toFixed(2);
      else this.warnForm.dayGain = null;
      if (Number(item.dayDecline) != 0)
        this.warnForm.dayDecline = (item.dayDecline * 100).toFixed(2);
      else this.warnForm.dayDecline = null;
      this.warnId = item.id;
      this.navKey = 1;
    },
    // 添加预警
    async setWarn() {
      // 新建预警
      let res;
      let reg = /^\d+(\.\d{0,4})?$/;
      let regs = /^\d+(\.\d{0,2})?$/;
      if (
        !this.warnForm.targetHigh &&
        !this.warnForm.targetLow &&
        !this.warnForm.dayGain &&
        !this.warnForm.dayDecline
      )
        return this.$message.error(this.$t("inccom.warn_dialog.56hz0lui51k0"));
      if (!reg.test(this.warnForm.targetHigh) && this.warnForm.targetHigh)
        return this.$message.error(this.$t("inccom.warn_dialog.56hz0lui55s0"));
      if (!reg.test(this.warnForm.targetLow) && this.warnForm.targetLow)
        return this.$message.error(this.$t("inccom.warn_dialog.56hz0lui58g0"));
      if (!regs.test(this.warnForm.dayGain) && this.warnForm.dayGain)
        return this.$message.error(this.$t("inccom.warn_dialog.56hz0lui5bg0"));
      if (!regs.test(this.warnForm.dayDecline) && this.warnForm.dayDecline)
        return this.$message.error(this.$t("inccom.warn_dialog.56hz0lui5dw0"));
      // 后台不能传空值
      if (this.warnForm.targetHigh == null) this.warnForm.targetHigh = "";
      if (this.warnForm.targetLow == null) this.warnForm.targetLow = "";
      if (this.warnForm.dayGain == null) this.warnForm.dayGain = "";
      if (this.warnForm.dayDecline == null) this.warnForm.dayDecline = "";
      if (this.warnId == "") {
        res = await post_warn({
          warnId: "",
          securityType: this.StockData.securityType,
          symbol: this.StockData.symbol,
          market: this.StockData.market,
          targetHigh: this.warnForm.targetHigh,
          targetLow: this.warnForm.targetLow,
          dayGain: this.warnForm.dayGain,
          dayDecline: this.warnForm.dayDecline,
          isWarn: 1,
          isNotice: 1,
        });
      } else {
        res = await post_warn({
          warnId: this.warnId,
          securityType: this.StockData.securityType,
          symbol: this.StockData.symbol,
          market: this.StockData.market,
          targetHigh: this.warnForm.targetHigh,
          targetLow: this.warnForm.targetLow,
          dayGain: this.warnForm.dayGain,
          dayDecline: this.warnForm.dayDecline,
          isWarn: 1,
          isNotice: 1,
        });
      }
      if (res.code != 1) return this.$message.error(res.msg);
      this.$store.dispatch("SetStockData", {
        securityType: this.StockData.securityType,
        symbol: this.StockData.symbol,
        market: this.StockData.market,
      });
      this.$store.dispatch(
        "SetEarlyWarningNum",
        this.$store.state.index.EarlyWarningNum + 1
      );
      (this.warnForm = {
        targetHigh: null,
        targetLow: null,
        dayGain: null,
        dayDecline: null,
      }),
        this.reflash();
      this.hide();
      return this.$message.success(res.msg);
    },
  },
  computed: {
    stockInfo() {
      return this.$store.state.index.stockInfo;
    },
    StockData() {
      return this.$store.state.index.StockData;
    },
  },
};
</script>

<style lang="less">
@import "~@/assets/less/common.less";
@import "~@/assets/less/search.less";
.el-dialog {
  background-color: @sideColor;
  .el-dialog__body {
    padding: 0 20px 20px 20px;
  }
}
.title_close {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .title {
    font-size: 14px;
    color: @fff;
    line-height: 28px;
    text-align: center;
  }
  .close {
    width: 18px;
    height: 18px;
    cursor: pointer;
  }
}
.warn_list {
  display: flex;
  justify-content: space-between;
  padding-bottom: 16px;
  .warn_bar {
    .warn_icon {
      margin-right: 5px;
      height: 20px;
    }
  }
  .el-autocomplete {
    width: 200px;
    height: 40px;
    .el-input {
      .el-input__inner {
        background-color: @deepBg;
        color: @fff;
        border: 1px solid transparent;
        border-radius: 3px;
        height: 30px;
      }
      .el-input__suffix {
        .el-input__suffix-inner {
          i {
            height: 30px;
            line-height: 30px;
          }
          img {
            height: 20px;
            line-height: 20px;
          }
        }
      }
    }
    input {
      color: @fff;
      border: none;
      background: none;
    }
  }
}
.warn_new {
  .stock_info {
    display: flex;
    // width: 300px;
    height: 40px;
    justify-content: flex-start;
    align-items: center;
    .stock_icon {
      padding-right: 10px;
      img {
        height: 14px;
      }
    }
    .stock_name {
      color: @fff;
      padding-left: 10px;
      font-size: 14px;
    }
    .stock_gain {
      margin-top: 1px;
      padding-left: 10px;
      font-size: 14px;
      vertical-align: middle;
    }
  }
  .warn_content {
    .warn_content_title {
      color: @fff;
      font-size: 12px;
      font-weight: 400;
      margin-bottom: 25px;
      margin-top: 20px;
    }
    .warn_form {
      display: flex;
      align-items: center;
      color: @fff;
      font-size: 12px;
      .form_item {
        flex: 1;
        margin-bottom: 30px;
        .form_title {
          display: inline-block;
          width: 90px;
          height: 30px;
          text-align: left;
        }
        input {
          border: 1px solid transparent;
          background-color: @deepBg;
          color: @fff;
          width: 190px;
          height: 30px;
          padding-left: 10px;
          box-sizing: border-box;
        }
        .form_unit {
          margin-left: 10px;
        }
      }
    }
  }
  .new_bt {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-bottom: 40px;
    padding-top: 20px;
    button {
      margin-right: 25px;
    }
  }
}
.warn_lists {
  .warn_lists_nav {
    margin-right: 16px;
    border-top: 1px solid @LightBorderLine;
    border-bottom: 1px solid @LightBorderLine;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .stock_sort {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 12px;
      .stock_item {
        cursor: pointer;
        padding-right: 40px;
        line-height: 30px;
        height: 32px;
      }
    }
  }
}

.hover {
  color: @hoverColor;
}
// .red {
//   color: @red;
// }
// .green {
//   color: @green;
// }
.reflash_icon {
  width: 20px;
}
.el-dialog {
  .el-dialog__header {
    padding-top: 10px
  }
}
</style>